<?php

//帐户模型
class Accounts_model extends Model {

	function Accounts_model()
	{
		parent::Model();	
		$this->load->database();
		$this->load->library("session");
		$this->load->library('smtp');
	}
	
	//编辑账户
	function edit($userid)
	{
		$limitlogin = p("limitlogin");
		$limitreason = p("limitreason");
		$status = p("status");
		if(strtotime($limitlogin)>time()) {
			$data = array(
				"limitlogin" => strtotime($limitlogin),
				"limitreason" => $limitreason,
				"status" => 3,
			);	
		} else {
			$data = array(
				"limitlogin" => 0,
				"status" => $status,
			);
		}
		$this->db->where("id", $userid);
		$result = $this->db->update("accounts", $data);
		return $result;
	}
	
	//删除单个账户
	function delete($id)
	{
		//删除会员
		$this->db->where("id", $id);
		$result = $this->db->delete("accounts");
		//删除关注
		$query = $this->db->get_where("fans", array("userid"=>$id));
		$fans = $query->result_array();
		foreach ($fans as $fan) {
			$siteid = $fan['siteid'];
			$this->ssm->update_fans($siteid, $id, "unset");
		}
		$result = $this->db->delete("fans", array("userid"=>$id));
		return $result;
	}
	
	//删除选择账户
	function delselected($delstr)
	{
		$delid = array();
		$_delid = explode("_", $delstr);
		//数组处理
		for ($i=0; $i<count($_delid); $i++) {
			if(intval($_delid[$i]) >0) {
				$delid[]= $_delid[$i];
			}
		}
		if(count($delid) == 0) return false;
		//删除会员
		$this->db->where_in("id", $delid);
		$result = $this->db->delete("accounts");
		//删除关注
		$this->db->from("fans");
		$this->db->where_in("userid", $delid);
		$query = $this->db->get();
		$fans = $query->result_array();
		foreach ($fans as $fan) {
			$siteid = $fan['siteid'];
			$this->ssm->update_fans($siteid, 0, "unset");
		}
		$this->db->where_in("userid", $delid);
		$result = $this->db->delete("fans");
		return $result;
	}
	
	//屏蔽选择账户
	function statusselected($delstr)
	{
		$delid = array();
		$_delid = explode("_", $delstr);
		//数组处理
		for ($i=0; $i<count($_delid); $i++) {
			if(intval($_delid[$i]) >0) {
				$delid[]= $_delid[$i];
			}
		}
		if(count($delid) == 0) return false;
		//屏蔽会员
		$data = array(
			"status" => 2,
		);
		$this->db->where_in("id", $delid);
		$result = $this->db->update("accounts", $data);
		return $result;
	}
	
	//获取列表
	function listitem($offset = 0, $pagecount = 20, $order = "id", $desc = "desc", $keyword = "")
	{
		$items = array();
//		$query = $this->db->from("accounts")->limit($pagecount, $offset)->order_by($order, $desc)->get();
		if($keyword == "") {//取出所有
			$this->db->from("accounts");
			if ($pagecount > 0) {//pagecount=0 取出所有
				$this->db->limit($pagecount, $offset);
			} 
			$query = $this->db->order_by($order, $desc)->get();
			if ($query->num_rows()>0) {
				$items = $query->result_array();
			}
		} else {//搜索账户
			$sql = "select *, replace(username,'$keyword', '<em class=word_s>$keyword</em>') as title from rn_accounts where LOCATE('$keyword', username)>0 order by id desc";
			if($pagecount > 0) {
				$sql .= " limit $offset,$pagecount";
			}
			$query = $this->db->query($sql);
			if ($query->num_rows()>0) {
				$items = $query->result_array();
			}
		}
		
		return $items;
	}
	
	//获取总数
	function countitems($keyword = "")
	{
		if($keyword == "") {//所有
			return $this->db->count_all_results("accounts");
		} else {//搜索
			$query = $this->db->query("select *, replace(username,'$keyword', '<em class=word_s>$keyword</em>') as title from rn_accounts where LOCATE('$keyword', username)>0");
			return $query->num_rows();
		}		
	}
	
	//注册
	function register($regdata = NULL)
	{
		if(is_null($regdata)) return false;
		//验证 ...
		//execute sql
		$data = array(
			"email" => $regdata["email"],
			"username" => $regdata["username"],
			"password" => md5($regdata["password"]),
			"regtime" => time(),
		);
		//a($data);
		$result = $this->db->insert("accounts", $data);
		
		//发送感谢邮件
		$mailsubject = "热闹网系统邮件";//邮件主题
		$mailbody = "您好，感谢您注册热闹网。请点击<a href='http://www.renao100.com/accounts' target='_blank'>登陆</a>。<br>了解更多关于热闹网信息，请进入热闹网：<a href='http://www.renao100.com' target='_blank'>http://www.renao100.com</a>";//邮件内容
		$mailtype = "HTML";//邮件格式（HTML/TXT）,TXT为文本邮件
		$this->smtp->debug = false;//是否显示发送的调试信息
		$send = $this->smtp->sendmail($regdata["email"], $mailsubject, $mailbody, $mailtype);
		return $result;
	} 
	
	//登陆
	function login($logindata = NULL, $forget = 0)
	{
		if(is_null($logindata)) return false;
		//验证是否重置密码
		if($forget == '1') {
			$query = $this->db->get_where("accounts", array("email"=>$logindata["email"], "forgetpwd"=>$logindata["password"], "status !="=>2));
		} else {//常规登陆
			$query = $this->db->get_where("accounts", array("email"=>$logindata["email"], "password"=>md5($logindata["password"]), "status !="=>2));
		}
		//a($query);
		if($query->num_rows()>0) {//登陆成功 -> session
			$account = $query->row_array();
			//检测是否限制访问
			if($account["limitlogin"] >= time()) {
				show_failed("账号限制访问：".$account["limitreason"]);
			}
			
			//验证是否重置密码: 更新密码
			if($forget == '1') {
				$data = array(
					"password" => md5($logindata["password"]),
				);
				$this->db->where('id', $account['id']);
				$this->db->update('accounts', $data);
			}
			
			$sess_data = array(
				"account_id" => $account["id"],
				"account_username" => $account["username"],
				"account_email" => $account["email"],
			);
			//a($sess_data);
			if(p("remember") == '1') {
				$sess_data["remember"] = 1;
			}
			$this->session->set_userdata($sess_data);
			//更新最后登陆时间
			$this->update_lastlogin($account["id"]);
			return $sess_data;
		} 
		return false;
	}
	
	//更新最后登陆时间
	function update_lastlogin($id)
	{
		$this->db->where("id", $id);
		$result = $this->db->update("accounts", array("lastlogin"=>time()));
		return $result;
	}
	
	//找回密码：发送邮件确认
	function forget($email = NULL)
	{
		if(is_null($email)) return false;
		//获取email账户信息
		$query = $this->db->get_where("accounts", array("email"=>$email));
		if($query->num_rows() == 0) show_failed("非法请求");
		$account = $query->row_array();
		
		//生成随机密码
		$password = generate_password(8);
		//记录随机密码
		$data = array(
			"forgetpwd" => $password,
		);
		$this->db->where("id", $account['id']);
		$this->db->update("accounts", $data);
		
		//生成验证链接
		$link = 'http://www.renao100.com/accounts/index/?forget='.$account['id'].'&do=1';
		
		//发送邮件
		$mailsubject = "热闹网系统邮件";//邮件主题
		$mailbody = "您好，此邮件为热闹网系统自动发送密码重置邮件。请点击<a href='".$link."' target='_blank'>验证链接</a>并用新密码登陆: <em>$password</em><br />验证链接：<a href='".$link."' target='_blank'>".$link."</a>";
		$mailtype = "HTML";//邮件格式（HTML/TXT）,TXT为文本邮件
		$this->smtp->debug = false;//是否显示发送的调试信息
		$this->smtp->sendmail($email, $mailsubject, $mailbody, $mailtype);
		
		return true;
	}
	
	//退出登陆
	function logout()
	{
//		$sess_data = array(
//			"account_id" => "",
//			"account_username" => "",
//			"account_email" => "",
//			"remember" => "",
//			"forward" => "",
//		);
//		$this->session->unset_userdata($sess_data);

		/* weibo logout */
		$sess_data = array(
	  		"account_id" => "",
	  		"account_username" => "",
	  		"account_email" => "",
  		);
  		setcookie("weibo", "", time()-3600, "/");
	}
	
	//检测登陆状态
	function is_logined()
	{
//		$account_id = $this->session->userdata("account_id");
//		if($account_id) return $account_id;
//		return 0;

		/* weibo login */
		if(isset($_COOKIE['weibo']) && is_array(@unserialize($_COOKIE['weibo']))){
			$weibo = unserialize($_COOKIE['weibo']);
			$account_id = $weibo['account_id'];
			if($account_id) return $account_id;
		}
		return 0;
	}
	
	//获取登陆信息
	function get_account()
	{
		if(!$this->is_logined()) return false;
//		$sess_data = array(
//			"account_id" => $this->session->userdata("account_id"),
//			"account_username" => $this->session->userdata("account_username"),
//			"account_email" => $this->session->userdata("account_email"),
//		);
//		$row = $this->get($this->session->userdata("account_id"));

		/* weibo login */
		$weibo = unserialize($_COOKIE['weibo']);
		$sess_data = array(
			"account_id" => $weibo['account_id'],
			"account_username" => $weibo['account_username'],
			"account_email" => $weibo['account_email'],
		);
		$row = $this->get($weibo['account_id']);

		if(is_array($row) && count($row)>0) {
			$sess_data = array_merge($sess_data, $row);
		} else {
			$this->logout();
			redirect('/');
		}
		return $sess_data;
	}
	
	//获取帐号信息
	function get($userid)
	{
		$query = $this->db->get_where("accounts", array("id"=>$userid));
		if($query->num_rows()>0) {
			return $query->row_array();
		}
		return false;
	}
	
	//更新信息(头像)
	function update_userdata($userid, $data)
	{
		$this->db->where("id", $userid);
		$result = $this->db->update("accounts", $data);
		return $result;
	}
	
	//检测密码
	function check_password($userid, $password)
	{
		$row = $this->get($userid);
		if($row["password"] != md5($password)) {
			return false;
		}
		return true;
	}
	
	//检测用户名是否存在
	function aj_exsits_username($userid, $username)
	{
		$query = $this->db->get_where("accounts", array("username"=>$username, "id !="=>$userid));
		if($query->num_rows()>0) {
			return true;
		} else {
			return false;
		}
	}
	
	//检测邮件地址是否存在
	function exsits_email($email)
	{
		$query = $this->db->get_where("accounts", array("email"=>$email));
		if($query->num_rows()>0) {
			return true;
		} else {
			return false;
		}
	}
	
	//检测用户名是否存在
	function exsits_username($username)
	{
		$query = $this->db->get_where("accounts", array("username"=>$username));
		if($query->num_rows()>0) {
			return true;
		} else {
			return false;
		}
	}
	
}

/* End of file */